#include "protocol.h"
#include <QJsonDocument>
#include <QDataStream>

QByteArray Protocol::createMessage(MessageType type, const QJsonObject& data) {
    QJsonObject message;
    message["type"] = static_cast<int>(type);
    message["data"] = data;
    
    QJsonDocument doc(message);
    QByteArray jsonData = doc.toJson(QJsonDocument::Compact);
    
    // 添加消息长度前缀
    QByteArray result;
    QDataStream stream(&result, QIODevice::WriteOnly);
    stream.setVersion(QDataStream::Qt_5_0);
    stream << static_cast<quint32>(jsonData.size());
    result.append(jsonData);
    
    return result;
}

bool Protocol::parseMessage(const QByteArray& data, MessageType& type, QJsonObject& jsonData) {
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    
    if (error.error != QJsonParseError::NoError || !doc.isObject()) {
        return false;
    }
    
    QJsonObject message = doc.object();
    if (!message.contains("type") || !message.contains("data")) {
        return false;
    }
    
    type = static_cast<MessageType>(message["type"].toInt());
    jsonData = message["data"].toObject();
    
    return true;
}

QJsonObject Protocol::createErrorResponse(const QString& error) {
    QJsonObject response;
    response["success"] = false;
    response["error"] = error;
    return response;
}

QJsonObject Protocol::createSuccessResponse(const QString& message) {
    QJsonObject response;
    response["success"] = true;
    response["message"] = message;
    return response;
}

